import Taro from '@tarojs/taro'
import {
  put, all, takeEvery, fork
} from 'redux-saga/effects'
import { LOGOUT_USER } from '@ACTIONS/auth'
import { LOGIN_FAILURE_MAP, DISABLE_LOGIN_FAILURE_MAP } from '@CONSTANTS/app'
import { GET_MED_RECORD } from '@ACTIONS/medRecord'

const FAILURE = 'FAILURE'
const DISABLED_TOAST = [GET_MED_RECORD.FAILURE]
function* handler(action) {
  let preError = ''
  let lastToastTime = new Date().getTime()
  const { type, error } = action
  if (!type.includes(FAILURE)) { return }
  if (DISABLED_TOAST.includes(type)) return
  if (error && LOGIN_FAILURE_MAP.includes(error.message || error)) {
    yield put({
      type: LOGOUT_USER.REQUEST,
      disableLogin: DISABLE_LOGIN_FAILURE_MAP.includes(type)
    })
    return
  }
  const lastError = `${error}`
  if (error && (preError !== lastError || new Date().getTime() - lastToastTime > 5000)) {
    preError = lastError
    const noNetwork = error.toString().includes('Network request failed') || error.toString().includes('Network Error')
    if (noNetwork) {
      Taro.showToast({
        icon: 'none',
        title: '请检查您的网络连接，然后重试。'
      })
    } else {
      Taro.showToast({
        icon: 'none',
        title: error.toString()
      })
    }
    lastToastTime = new Date().getTime()
  }
}

export function* watchAll() {
  yield takeEvery('*', handler)
}

export default function* rootSaga() {
  yield all([fork(watchAll)])
}
